<template>
  <el-card class="box-card">
    <div slot="header">
      <span>修改密码</span>
    </div>
    <el-form ref="ruleForm" v-loading.body="loading" label-width="80px" :model="password" :rules="rules">
      <el-form-item label="旧密码" prop="old">
        <el-input v-model="password.old" type="password" placeholder="请输入旧密码" @keyup.enter.native="submit" />
      </el-form-item>
      <el-form-item label="新密码" prop="new">
        <el-input v-model="password.new" type="password" placeholder="请输入新密码，长度6位以上" @keyup.enter.native="submit" />
      </el-form-item>
      <el-form-item label="重复密码" prop="confirm">
        <el-input v-model="password.confirm" type="password" placeholder="再次输入新密码" @keyup.enter.native="submit" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit()">修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import * as user from '@/api/user'
export default {
  data() {
    return {
      loading: false,
      password: {},
      rules: {
        old: [{
          required: true,
          message: '请输入旧密码',
          trigger: 'blur'
        }],
        new: [{
          required: true,
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请输入新密码'))
            } else if (this.password.new.length < 6) {
              callback(new Error('密码长度不足6位'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        confirm: [{
          required: true,
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请再次输入密码'))
            } else if (value !== this.password.new) {
              callback(new Error('两次输入不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }]
      }
    }
  },
  created: function() {},
  methods: {
    submit: function() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true
          // 验证通过
          this.update()
        }
      })
    },
    update: function() {
      user.update(this.password).then(response => {
        // 保存token到前端
        console.log(response)
        this.$message({
          type: 'success',
          message: response.msg,
          onClose: () => {
            this.$store.dispatch('user/logout')
              .then(() => {
                this.$router.push({ path: '/login' })
              })
          }
        })
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>
